import { UI } from '@hyext/hy-ui'
import React, { Component } from 'react'
import './app.hycss'
import './assets/css/SelectGift.hycss'
import {
  TouchableWithoutFeedback
} from 'react-native'

import {sendYz, setResult} from '../utils/request'
import {getUserResult, changeToIndex, changeName} from '../utils/request'
import {getOrders} from '../utils/request'
import IMG from '../img/img'
import Yz_item_view from "../giftsender-app_streamer/component/yz_item_view"
import { ImageBackground } from 'react-native';
const hyExt = global.hyExt

const { View, Text, Button, ScrollView, Image } = UI

class App extends Component {
  constructor(initialProps) {
    super();
    this.$refs = React.createRef()
    this.state = {
      btn_able: false,
      counted_result:'', 
      msg: '1',
      start_str: '0',
      giftInfo: [],
      giftIndex: 1,
      giftNum: 1,
      emit_info: '215454',
      textBar: "174989",
      list_view: [],
      list: [],
      time: 60, 
      timer: {}, 
      userInfo: '{"userUnionId":"111"}',
      show_result_view: [],
      my_result: 0
    }
  }
  //将主播传过来的数据设置到state的list中
  setDataToList(res){
    var res1 = JSON.parse(res)
      this.state.list = []
      for (var i = 0; i < res1.data.length; i++){
        let ab = {name: res1.data[i], num: 0}
        this.state.list.push(ab)
      }
  }//setDataToList end
  messageEventListener(){
    hyExt.observer && hyExt.observer.on('yz', res => {
      console.log("[message]:监听到主播打开押注局",res);
      // [message]: {"data":["PX","YE","XM","TQ"],"time":"10"}
      //开局初始化数据
      this.setState({start_str: '1'})
      this.setState({btn_able: false})
      this.setDataToList(res)
      this.show_info()
      this.my_time()
      this.setState({userInfo: '{"userUnionId":"111"}'})
      //从虎牙存储中获取当前主播传过来的押注项，并设置到list中
      hyExt.storage.getItem("list").then(value=>{
        this.setDataToList(value)
        this.show_info()  
        console.log("获取主播传过来的设置好的押注项成功")
      }).catch(err=>{
        console.log("获取主播传来的设置好的押注项失败")
      })
    })
    console.log("注册广播监听完成")
  }


  componentDidMount() {
    
    //虎牙小程序加载
    hyExt.onLoad && hyExt.onLoad(()=> {
      this.messageEventListener();    
      console.log("虎牙onload加载小程序完成")
    });
    
    //获取存储键time
    // hyExt.storage.getItem('time').then(value => {  
    //   this.state.time = value
    // }).catch(err => {
    // })
    //设置初始化状态
    hyExt.storage.getItem('start_str').then(value => {  
      this.setState({start_str: value})
      if(value == '1'){
        this.my_time()
        this.show_info()
        //从虎牙存储中获取当前主播传过来的押注项，并设置到list中
        hyExt.storage.getItem("list").then(value=>{
          this.setDataToList(value)
          this.show_info()  
          console.log("获取主播传过来的设置好的押注项成功")
        }).catch(err=>{
          console.log("获取主播传来的设置好的押注项失败")
        })
      }
      console.log("当前观众状态："+this.state.start_str)
    }).catch(err => {
      console.log("获取虎牙存储中的观众状态错误："+err)
    })
    console.log("mount 加载完成")
  }//componentDidMount end

  show_info(){
    console.log("show_info()")
    var list_view_inner = this.state.list.map((item, index)=>{
      var indexs = changeToIndex(item.name)
      return (
      <ImageBackground className="container_m" source={require('../img/back.gif')}>
        <Text className="selectText">{item.name}</Text>
        <Image src = {IMG.list[indexs]} mode = 'cover'></Image>
        <TouchableWithoutFeedback onPress = {()=>{
          if(this.state.list[index].num>0){
            this.state.list[index].num -=1
          }
          this.show_info()
          console.log("点击-")
        }}>
          <View className="left"></View>
        </TouchableWithoutFeedback>
        <TouchableWithoutFeedback  onPress = {()=>{
          this.state.list[index].num +=1
          console.log("点击+")
          this.show_info()
        }}>
          <View className="right"></View>
        </TouchableWithoutFeedback > 
        <Text className="selectText">{item.num}</Text>
      </ImageBackground>
      )
    })
    this.setState({list_view: list_view_inner})
  }//show_info end

//mytime
  my_time(){
    this.timer && clearTimeout(this.timer);
    this.timer = setInterval(()=>{
      hyExt.storage.getItem('time').then(value => {  
        this.setState({time: value})
        if(value <= 0){
          console.log("时间为零：主播开奖")
          this.setState({start_str: 'result'})
          let userinfo_1 = JSON.parse(this.state.userInfo)
          getUserResult(userinfo_1.userUnionId, this)
          //获取虎牙存储中的counted_result
          hyExt.storage.getItem("counted_result").then(value=>{
            this.setState({counted_result: value})
          })
          //设置开奖结果押注项
          //从虎牙存储中获取已经计算过的结果并设置到state中
          hyExt.storage.getItem('counted_result').then(result=>{
            result = JSON.parse(result)
            let abc = result.result.map((item, index)=>{
              let indexs = changeToIndex(item)
              return (<Yz_item_view index = {indexs} img = {IMG}  item = {item}></Yz_item_view>)
            })
            this.setState({show_result_view: abc})
          }).catch(err=>{
            console.log("获取开奖的结果失败"+err)
          })
          //停止定时器
          console.log("停止定时器")
          this.timer && clearTimeout(this.timer);
        }
      }).catch(err => {
        console.log("*****************************"+"getItem失败观众端***严重***************************")
        console.log(err+"错误信息")
      })
      console.log("定时器监听中")
    }, 1000)
  }//mytime

  my_submit(){
    this.setState({btn_able: true})

    //获取观众uid并设置到state
    hyExt.context.getUserInfo().then(userInfo => {
      console.log("获取用户信息成功"+JSON.stringify(userInfo))
      this.setState({userInfo: JSON.stringify(userInfo)})
      //获取我的数据，包括我押注的数据
      console.log("submit")
      console.log(this.state.userInfo)
      console.log("submit")
      let myuserinfo = JSON.parse(this.state.userInfo)
      changeName(this.state.list)
      let data = {userNick: myuserinfo.userNick, userUnionId: myuserinfo.userUnionId, 
        yz_data: this.state.list
      }
      //发送数据到云，押注提交
      let kk = JSON.stringify(data)
      console.log(kk)
      sendYz(kk)
      console.log("提交押注成功")
      this.setState({start_str: 'wait'})
    }).catch(err => {
      console.log("获取用户信息失败")
    })
  }//my_submit

  initRender(){
    return (
      // <View className = "init_contain">
        // <ImageBackground className = "init_contain" source={require('../img/gz_pre3.jpg')}>
          <ImageBackground className = "init_contain" source={require('../img/back.jpg')}>
          <Text className = "init_render_text">游戏未开始，请稍等！！！</Text>
        </ImageBackground>
      // </View>
    )
  }
  renderHasSubmit(){
    return(
      <ImageBackground className = "wait_contain" source={require('../img/back.jpg')}>
        <Text className = "wait_text">你已经提交！请等待游戏结果~~~</Text>
      </ImageBackground>
      // <View className = "wait_contain">
      //   <Text className = "wait_text">你已经提交！请等待游戏结果~~~</Text>
      // </View>
    )
  }
  renderResult(){

    return (
      <ImageBackground className = "result_contain" source={require('../img/gz_res.jpg')}>
        <Text className = "kj_result">最终结果：</Text>
          <ScrollView>{this.state.show_result_view}</ScrollView>
        <Text className = "mydef">我的得分为：{this.state.my_result}</Text>
      </ImageBackground>
      // <View className = "result_contain">
      //   <Text className = "kj_result">最终结果：</Text>
      //   <ScrollView>{this.state.show_result_view}</ScrollView>
      //   <Text className = "mydef">我的得分为：{this.state.my_result}</Text>
      // </View>
    )
  }
  render () {

    if(this.state.start_str == '0'){
      return this.initRender()
    }else if(this.state.start_str == '1'){
    return (
      <ImageBackground className = "game" source={require('../img/back.jpg')}>
        <Text className = "game_top_text">游戏进行中</Text>
        <View className = "scrol" >
          <ScrollView nestedScrollEnabled={true} scrollViewRef={this.$refs} >  
            {this.state.list_view}
          </ScrollView>
        </View>
        <View>
          <Button className = "y_btn" disabled = {this.state.btn_able} onPress = {()=>{
              this.my_submit()
          }} ><Text className = "ybtn_text" >提交我的选择</Text></Button>
          <Text>{this.state.msg}</Text>
        </View>
      </ImageBackground>
      // <View className = "game">
      //   <Text className = "game_top_text">游戏进行中</Text>
      //   <View className = "scrol" >
      //     <ScrollView nestedScrollEnabled={true} scrollViewRef={this.$refs} >  
      //       {this.state.list_view}
      //     </ScrollView>
      //   </View>
      //   <View>
      //     <Button className = "y_btn" onPress = {()=>{
      //         this.my_submit()
      //     }} ><Text className = "ybtn_text" >提交我的选择</Text></Button>
      //     <Text>{this.state.msg}</Text>
      //   </View>
      // </View>
    )}else if(this.state.start_str == 'wait'){
      return this.renderHasSubmit()
    }else return this.renderResult()
  }
}

export default App
